package com.gm.wholesale.module.order.ui.needOrder;

import android.net.http.SslError;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment;
import com.gm.commonlib.module.evenbus.EventBusUtils;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.module.print.PrintUtil;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog;
import com.gm.commonlib.views.superview.SuperTextView;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.BuildConfig;
import com.gm.wholesale.R;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.order.api.IOrderApi;
import com.gm.wholesale.module.order.bean.OrderBean;
import com.gm.wholesale.module.order.bean.needorder.AcceptOrderIdsReq;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean;
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime;
import com.gm.wholesale.module.order.model.NeedOrderModel;
import com.gm.wholesale.module.order.orderStatus.NeedOrderStatusType;
import com.gm.wholesale.module.order.ui.OrderMangerFragment;
import com.gm.wholesale.module.user.UserDataManger;
import com.gm.wholesale.util.ViewUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;

public class NeedOrderListFragment extends BaseListFragment<NeedOrderBean, BasePageData<NeedOrderBean>> implements ISearchOrderByTime {

    private String mOrderingTimeBegin;
    private String mOrderingTimeEnd;

    private OrderMangerFragment mOrderMangerFragment;

    private boolean mIsAllCheck;
    private List<NeedOrderBean> mChoiceData = new ArrayList<>();
    private LinearLayout allChoiceView;
    private ImageView allChoiceImage;
    private SuperTextView mPrintView;
    private TextView allChoiceTv;
    private WebView mWebView;

    public void updateView() {
        mOrderingTimeBegin = null;
        resetFooterView();
        refreshData();

    }

    @Override
    public void onRefreshView() {
        super.onRefreshView();
        resetFooterView();
    }

    @Override
    public void initPullToRefreshListView() {
        super.initPullToRefreshListView();
        mIsShowToast = false;
        setBodybg(getResources().getColor(R.color.white));
        pullToRefreshListView.setDivider(getResources().getDrawable(R.drawable.list_driver_shap));

    }

    @Override
    protected void onCreateContentFooter(ViewGroup parent) {
        super.onCreateContentFooter(parent);
        View view = LayoutInflater.from(context).inflate(R.layout.view_need_order_fouter, parent);
        allChoiceView = view.findViewById(R.id.allChoice);
        allChoiceImage = view.findViewById(R.id.choiceImage);
        mPrintView = view.findViewById(R.id.printTv);
        allChoiceTv=view.findViewById(R.id.allChoiceTv);
        mWebView = view.findViewById(R.id.webView);
        ViewUtil.initWebView(mWebView);
        allChoiceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDatas.isEmpty()){
                    ToastUtil.showToast("没有订单");
                    return;
                }
              //  allChoiceImage.setImageResource(mIsAllCheck ? R.drawable.gou_uncheck : R.drawable.gou_check);
                mIsAllCheck = !mIsAllCheck;
                changeDataChoiceState();
                changeFooterView();
            }
        });
        mPrintView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 if (RepeatClickUtils.check()){
                   return;
                  }
                if (mChoiceData.isEmpty()) {
                    ToastUtil.showToast("请先勾选订单");
                } else {
                    loadUrl();
                }
            }
        });

    }

    private void resetFooterView(){
        mChoiceData.clear();
        mIsAllCheck=false;
        allChoiceImage.setImageResource(R.drawable.gou_uncheck);
        allChoiceTv.setText("全选");
    }

    private void print() {
        LogUtil.d("printprintprint");
        try {
            PrintUtil.createWebPrintJob(context, mWebView, result -> {
                if (result) { //打印成功发送给打印机了，默认表示打印了,改变订单状态
                    ArrayList<Long> ids=new ArrayList<>();
                    for (NeedOrderBean orderBean : mChoiceData) {
                        //状态未接单得，才去调用接口 该状态
                        if (orderBean.getStatus() == NeedOrderStatusType.DJD.getType()){
                            ids.add(orderBean.getNeedsId());
                        }
                    }
                    //todo 空的话说明 都是已接单的。直接刷新ui，不用去修改单子状态
                    if (ids.isEmpty()){
                        refreshData();
                        resetFooterView();
                        return;
                    }
                    AcceptOrderIdsReq data=new AcceptOrderIdsReq();
                    data.setNeedsIDs(ids);
                 NeedOrderModel.acceptOrders(data, (IBaseView) getActivity(), new BaseHttpObserver<BaseResp>() {

                     @Override
                     public void onComplete() {
                         resetFooterView();
                         refreshData();
                     }
                 });
                }
            });
        } catch (Exception e) {
            ToastUtil.showToast("设备不支持打印功能");
        }


    }

    public void loadUrl() {
        StringBuilder ids = new StringBuilder("");
        for (NeedOrderBean orderBean : mChoiceData) {
            if (TextUtils.isEmpty(ids)) {
                ids.append(orderBean.getNeedsId());
            } else {
                ids.append(",");
                ids.append(orderBean.getNeedsId());
            }

        }
        LoadingDialog.newLoadingDialog().show(getActivity());
        String url = BuildConfig.WEB_HOST + "order_receive_print?needsIds=" + ids + "&token=" + UserDataManger.newInstance().getToken();

        mWebView.loadUrl(url);
        mWebView.setWebViewClient(new WebViewClient() {
                                      @Override
                                      public void onPageFinished(WebView view, String url) {
                                          LoadingDialog.newLoadingDialog().hid();
                                          if (view.getProgress()>=100){
                                              print();
                                          }

                                      }

                                      @Override
                                      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                                          super.onReceivedError(view, errorCode, description, failingUrl);
                                          ToastUtil.showToast(description);
                                          LoadingDialog.newLoadingDialog().hid();
                                      }

                                      @Override
                                      public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                          LogUtil.d("shouldOverrideUrlLoading");
                                          view.loadUrl(url);
                                          return true;

                                      }

                                      @Override
                                      public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                          handler.proceed();
                                          LoadingDialog.newLoadingDialog().hid();
                                          super.onReceivedSslError(view, handler, error);
                                      }

                                      @Override
                                      public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                                          LoadingDialog.newLoadingDialog().hid();
                                          super.onReceivedHttpError(view, request, errorResponse);
                                      }

                                  }


        );
    }

    private void changeDataChoiceState() {
        mChoiceData.clear();
        for (NeedOrderBean orderBean : mDatas) {
            orderBean.setmIsCheck(mIsAllCheck);
        }
        if (mIsAllCheck) {
            mChoiceData.addAll(mDatas);
        }
        notifyListDataSetChanged();
    }

    public void setOrderMangerFragment(OrderMangerFragment orderMangerFragment) {
        mOrderMangerFragment = orderMangerFragment;
    }


    @Override
    protected void getDataFinish(List<NeedOrderBean> mDatas) {
        if (mDatas != null && !mDatas.isEmpty()) {
            mDatas.get(0).setClick(true);
            showOrderDetail(mDatas.get(0));
        } else {
            if (mOrderMangerFragment != null) {
                mOrderMangerFragment.hidNeedOrderDetailView();
            }
        }
    }

    @Override
    protected BaseAdapter createTempBaseAdapter() {
        return new CommonAdapter<>(getActivity(), mDatas, R.layout.list_need_order_item) {
            @Override
            public void convert(ViewHolder viewHolder, final NeedOrderBean data) {
                if (data.isChanged()) {
                    viewHolder.getView(R.id.hasUpdateTv).setVisibility(View.VISIBLE);
                } else {
                    viewHolder.getView(R.id.hasUpdateTv).setVisibility(View.GONE);
                }
                if (data.isClick()) {
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.color_e4f4eb));
                } else {
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.white));
                }
                viewHolder.setText(R.id.orderNameTv, data.getCustomerName());
                viewHolder.setText(R.id.orderNumTv, data.getNeedsNo());
                viewHolder.setText(R.id.createTimeTv, data.getCreateTime());
                ImageView imageView = viewHolder.getView(R.id.choiceImage);
                if (data.ismIsCheck()) {
                    imageView.setImageResource(R.drawable.gou_check);
                } else {
                    imageView.setImageResource(R.drawable.gou_uncheck);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        data.setmIsCheck(!data.ismIsCheck());
                        handelChoiceImageClick(data);
                        notifyListDataSetChanged();
                    }
                });
                TextView orderStateTv = viewHolder.getView(R.id.orderStateTv);
                TextView redNtTv = viewHolder.getView(R.id.redNtTv);
                showOrderState(data, orderStateTv, redNtTv);
                viewHolder.getConvertView().setOnClickListener(v -> {
                    setDataClick(data);
                    showOrderDetail(data);
                });
            }
        };

    }

    private void handelChoiceImageClick(NeedOrderBean orderBean) {
        if (mChoiceData.isEmpty()) {
            mChoiceData.add(orderBean);
            changeFooterView();
            return;
        }
        boolean hasExit = false;
        for (NeedOrderBean needOrderBean : mChoiceData) {
            if (needOrderBean.getNeedsId() == orderBean.getNeedsId()) {
                hasExit = true;
                break;
            }
        }
        //不存在添加
        if (!hasExit) {
            mChoiceData.add(orderBean);
        } else {
            mChoiceData.remove(orderBean);
        }
        changeFooterView();
    }

    private void changeFooterView() {
        if (mChoiceData.size() == mDatas.size()) {
            allChoiceTv.setText("取消全选");
            allChoiceImage.setImageResource(R.drawable.gou_check);
            mIsAllCheck = true;
        } else {
            allChoiceTv.setText("全选");
            allChoiceImage.setImageResource(R.drawable.gou_uncheck);
            mIsAllCheck = false;
        }
    }

    private void showOrderState(NeedOrderBean data, TextView textView, TextView redNtTv) {
        if (data.getStatus() == NeedOrderStatusType.DJD.getType()) {
            textView.setText("未打印");
            textView.setTextColor(context.getResources().getColor(R.color.color_FF4D4F));
            redNtTv.setVisibility(View.VISIBLE);
        } else if (data.getStatus() == NeedOrderStatusType.YJD.getType()) {
            textView.setText("已打印");
            textView.setTextColor(context.getResources().getColor(R.color.color_06AE56));
            redNtTv.setVisibility(View.GONE);
        } else {
            textView.setText("已回执");
            textView.setTextColor(context.getResources().getColor(R.color.color_06AE56));
            redNtTv.setVisibility(View.GONE);
        }
    }


    private void showOrderDetail(NeedOrderBean needOrderBean) {
        EvenBusUtil.showNeedOrderDetail(needOrderBean);
    }


    private void setDataClick(NeedOrderBean clickData) {
        for (NeedOrderBean data : mDatas) {
            if (data.getNeedsId() == clickData.getNeedsId()) {
                data.setClick(true);
            } else {
                data.setClick(false);
            }
        }
        notifyListDataSetChanged();


    }


    @Override
    protected HttpServicesHolder<?, BasePageData<NeedOrderBean>> getHttpServicesHolder(long index) {
        return new HttpServicesHolder<IOrderApi, BasePageData<NeedOrderBean>>() {
            @Override
            public Observable<BasePageData<NeedOrderBean>> getHttpObservable(IOrderApi api) {
                ArrayMap<String, Object> quearyData = getArrayMap();
                quearyData.put("page", index);
                quearyData.put("pageSize", Constant.DEFAULTPAGESIZE);
                return api.getNeedOrderList(quearyData);
            }
        };
    }

    public void getUnReviceOrderSize() {
        NeedOrderModel.getUnReviceOrderSize(getArrayMap(), new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<Long> resp) {
                if (resp != null && mOrderMangerFragment != null) {
                    mOrderMangerFragment.showRedUnReviceOrderSize(resp.getData());
                }
            }

            @Override
            protected void onError(String error) {

            }
        });
    }

    public ArrayMap<String, Object> getArrayMap() {
        //订单类型，1-小程序现场单，2-小程序提前单，3-批发版现场单
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("type", 3);
        if (TextUtils.isEmpty(mOrderingTimeBegin)) {
            mOrderingTimeBegin = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
            mOrderingTimeEnd = mOrderingTimeBegin + " 23:59:59";
            mOrderingTimeBegin = mOrderingTimeBegin + " 00:00:00";
        }
        queryData.put("createTimeStart", mOrderingTimeBegin);
        queryData.put("createTimeEnd", mOrderingTimeEnd);


        return queryData;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        getUnReviceOrderSize();
        int code = event.getCode();
        //修改状态未已打印
        if (code == EventBusType.UPDATE_NEED_ORDER_LIST_ITEM.getType()
                || code == EventBusType.UPDATE_NEED_ORDER_DETAIL.getType()) {
            updateItemView((NeedOrderBean) event.getData());
        }


    }


    public void updateItemView(NeedOrderBean needOrderBean) {
        for (NeedOrderBean orderBean : mDatas) {
            if (needOrderBean.getNeedsId() == orderBean.getNeedsId()) {
                orderBean.setStatus(needOrderBean.getStatus());
                orderBean.setChanged(needOrderBean.isChanged());
                notifyListDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void searchOrderByTime(String begTime, String endTime) {
        mOrderingTimeBegin = begTime;
        mOrderingTimeEnd = endTime;
        getUnReviceOrderSize();
        refreshData();

    }

    public String getTime() {
        if (mOrderingTimeBegin == null) return null;
        Date date = DateTimeUtils.formatDateTime(mOrderingTimeBegin, DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
        return DateTimeUtils.formatDateTime(date, DateTimeUtils.HMD2);
    }


}
